package cn.stylefeng.guns.modular.rest.movesupport;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

import cn.stylefeng.guns.modular.basic.entity.*;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.storage.model.result.StoragePutSingleResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.app.model.params.MovingPalletsmergeParam;
import cn.stylefeng.guns.modular.app.service.MovingPalletsmergeService;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicTrayParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicTrayResult;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.storage.service.StorageStockDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 移库合托
 */
@Controller
@RequestMapping("/rest/movesupport")
public class restMovesupportController extends BaseController{

    @Autowired
    private StorageStockService storageStockService;
    
    @Autowired
    private UserAop userAop;

    @Resource
    private BasicTrayService basicTrayService;

    @Autowired
    private MovingPalletsmergeService movingPalletsmergeService;

    @Autowired
    private BasicCustomerService basicCustomerService;
    /**
     * 根据库位查询商品信息
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseData list(StorageStockParam storageStockParam) {
    	User user = userAop.getUser();
    	if(ToolUtil.isNotEmpty(storageStockParam.getPositionNumber())) {
    		BasicPositionParam basicPositionParam = new BasicPositionParam();
    		basicPositionParam.setPositionNumber(storageStockParam.getPositionNumber());
    		basicPositionParam.setDeliverId(user.getDeliverId());
    		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(),user.getOperateId());
    		if(basicPositionResult == null) {
    			return ResponseData.error("库位不存在！");
    		} else {
    			storageStockParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
    		}
    	}
    	
        storageStockParam.setDeliverId(user.getDeliverId());
        storageStockParam.setDeptId(user.getDeptId());
        List<StorageStockResult> iii = this.storageStockService.findGoodsList(storageStockParam,user.getOperateId());
        for (StorageStockResult r : iii) {
        	storageStockParam.setPositionId(r.getPositionId());
        	storageStockParam.setGoodsbatchs(r.getGoodsbatchs());
        	storageStockParam.setGoodsId(r.getGoodsId());
        	r.setList(this.storageStockService.findTrayList(storageStockParam));
		}
        return ResponseData.success(iii);
    }


    /**
     * 根据库存ID获取库存信息
     * @param storageStockParam
     * @return
     */
    @RequestMapping("/listById")
    @ResponseBody
    public ResponseData listById(StorageStockParam storageStockParam) {
        if(ToolUtil.isEmpty(storageStockParam.getId())){
            ResponseData.error("参数不正确，请检查");
        }
        List<StorageStockResult> iii = this.storageStockService.findGoodsList(storageStockParam,null);
        for (StorageStockResult r : iii) {
            storageStockParam.setPositionId(r.getPositionId());
            storageStockParam.setGoodsbatchs(r.getGoodsbatchs());
            storageStockParam.setGoodsId(r.getGoodsId());
            r.setList(this.storageStockService.findTrayList(storageStockParam));
        }
        return ResponseData.success(iii);
    }

    @Autowired
    private BasicPositionService basicPositionService;

    @Autowired
    private BasicAreaService basicAreaService;

    @Autowired
    private StorageStockDetailedService storageStockDetailedService;

    /**
     * 移库
     * @param ids
     * @param aimpositionId
     * @return
     */
    @ResponseBody
    @RequestMapping("/remove")
    @Transactional(rollbackFor = Exception.class)
    public ResponseData remove(Long[] ids, Long aimpositionId,String aimpositionNumber) {
    	User user = userAop.getUser();
    	if(ToolUtil.isEmpty(aimpositionId)) {
    		if(ToolUtil.isNotEmpty(aimpositionNumber)) {
    			BasicPositionParam basicPositionParam = new BasicPositionParam();
    			basicPositionParam.setPositionNumber(aimpositionNumber);
    			basicPositionParam.setDeliverId(user.getDeliverId());
    			BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(),user.getOperateId());
    			if(basicPositionResult == null) {
    				return ResponseData.error("目的库位不存在！");
    			} else {
    				aimpositionId = Long.parseLong(basicPositionResult.getId().toString());
    			}
    		} else {
				return ResponseData.error("请选择目的库位！");
    		}
    	}
    	
        Long deliverid = user.getDeliverId();
        Long deptid = user.getDeptId();
        StorageStockParam storagestockparam = new StorageStockParam();
        StorageStockParam storagestocks = new StorageStockParam();//新库存
        StorageStockParam storagestockss = new StorageStockParam();//原始库存
        for (Long id : ids) {
            StorageStock sstockp = storageStockService.getById(id);//源
            if(sstockp.getPositionId().equals(aimpositionId)) {
            	continue;
            }
            ToolUtil.copyProperties(sstockp, storagestockparam);
            List<StorageStockResult> storagestockresult= storageStockService.findListBySpec(storagestockparam,user.getOperateId());//源
            BasicPosition basicposition = basicPositionService.getById(aimpositionId);
            if (basicposition == null) {
                return ResponseData.error("数据错误");
            }
            Integer areaid = basicposition.getPositionAreaId();//库区id
            BasicArea basicArea = basicAreaService.getById(areaid);
            if (basicArea == null) {
                return ResponseData.error("数据错误");
            }
            Long warehouseId = basicArea.getAreaWarehouseId().longValue();
            String warehouseName = basicArea.getAreaWarehouseName();
            Long areaId = areaid.longValue();
            String areaNumber = basicposition.getAreaNumber();
            String positionNumber = basicposition.getPositionNumber();
            for (int i = 0; i < storagestockresult.size(); i++) {
                ToolUtil.copyProperties(storagestockresult.get(i), storagestocks);
                ToolUtil.copyProperties(storagestockresult.get(i), storagestockss);
                storagestocks.setWarehouseId(warehouseId);//目的仓库id
                storagestocks.setWarehouseName(warehouseName);//目的仓库编号
                storagestocks.setAreaId(areaId);//目的库区id
                storagestocks.setAreaNumber(areaNumber);//目的库区编号
                storagestocks.setPositionId(aimpositionId);//目的库位id
                storagestocks.setPositionNumber(positionNumber);//目的库区编好
                storagestocks.setUpdateUser(user.getUserId());
                storagestocks.setDeliverId(deliverid);//交付id
                storagestocks.setDeptId(deptid);//部门id


                BasicCustomer basicCustomer = basicCustomerService.getById(storagestocks.getCustomerId());
                //是否储位限品
                if(ToolUtil.isNotEmpty(basicCustomer.getStorageLimitFlag()) && basicCustomer.getStorageLimitFlag().equals("是")) {
                        ResponseData responseData = storageStockService.storageLimitItems(user, positionNumber, warehouseId,storagestocks.getGoodsNo(),storagestocks.getGoodsNumber(),storagestocks.getGoodsbatchs());
                        if(responseData.getCode() == 500) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                            return responseData;
                        }
                }



                storageStockService.update(storagestocks);
                
                storageStockDetailedService.addNewDetailed("移库", "", "移出", "目的地："+positionNumber, storagestockss,user);
                storageStockDetailedService.addNewDetailed("移库", "", "移入", "源库位："+storagestockss.getPositionNumber(), storagestocks,user);
                
                MovingPalletsmergeParam movingPalletsmergeParam = new MovingPalletsmergeParam();
                //源
                movingPalletsmergeParam.setSourcewarehouseId(storagestockss.getWarehouseId());
                movingPalletsmergeParam.setSourcewarehouseName(storagestockss.getWarehouseName());
                movingPalletsmergeParam.setSourcepositionId(storagestockss.getPositionId());
                movingPalletsmergeParam.setSourcepositionNumber(storagestockss.getPositionNumber());
                movingPalletsmergeParam.setSourceareaId(storagestockss.getAreaId());
                movingPalletsmergeParam.setSourceareaNumber(storagestockss.getAreaNumber());
                movingPalletsmergeParam.setSourcetrayId(storagestockss.getTrayId());
                movingPalletsmergeParam.setSourcetrayNumber(storagestockss.getTrayNumber());
                movingPalletsmergeParam.setSourcenum(storagestockss.getNum());
                //商品
                movingPalletsmergeParam.setGoodsId(storagestockss.getGoodsId());
                movingPalletsmergeParam.setGoodsName(storagestockss.getGoodsName());
                movingPalletsmergeParam.setGoodsNumber(storagestockss.getGoodsNumber());
                BasicGoods basicGoodsff = basicGoodsService.getById(storagestockss.getGoodsId());
                movingPalletsmergeParam.setGoodsNo(basicGoodsff.getGoodsNo());
                //目的
                movingPalletsmergeParam.setAimwarehouseId(warehouseId);
                movingPalletsmergeParam.setAimwarehouseName(warehouseName);
                movingPalletsmergeParam.setAimpositionId(aimpositionId);
                movingPalletsmergeParam.setAimpositionNumber(positionNumber);
                movingPalletsmergeParam.setAimareaId(areaId);
                movingPalletsmergeParam.setAimareaNumber(areaNumber);
                movingPalletsmergeParam.setAimtrayId(storagestockss.getTrayId());
                movingPalletsmergeParam.setAimtrayNumber(storagestockss.getTrayNumber());
                movingPalletsmergeParam.setAimnum(storagestockss.getNum());
                movingPalletsmergeParam.setDeliverId(deliverid);
                movingPalletsmergeParam.setDeptId(deptid);
                movingPalletsmergeParam.setTypr("移库");
                movingPalletsmergeParam.setNodes(user.getName());
                movingPalletsmergeService.add(movingPalletsmergeParam);//添加记录
            }
        }
        return ResponseData.success();
    }
    
    @Autowired
    private BasicGoodsService basicGoodsService;

    /**
     * 移库功能(添加新托盘)
     * @return sourcepositionId 源
     * aimpositionId 目的地库位id
     */
    @RequestMapping("/execute")
    @ResponseBody
    public ResponseData execute(Long[] _idlist,Long[] _glist,String[] _numlist, Long aimpositionId,String aimpositionNumber) {
    	User user = userAop.getUser();
    	if(ToolUtil.isEmpty(aimpositionId)) {
    		if(ToolUtil.isNotEmpty(aimpositionNumber)) {
    			BasicPositionParam basicPositionParam = new BasicPositionParam();
    			basicPositionParam.setPositionNumber(aimpositionNumber);
    			basicPositionParam.setDeliverId(user.getDeliverId());
    			BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(),user.getOperateId());
    			if(basicPositionResult == null) {
    				return ResponseData.error("目的库位不存在！");
    			} else {
    				aimpositionId = Long.parseLong(basicPositionResult.getId().toString());
    			}
    		} else {
				return ResponseData.error("请选择目的库位！");
    		}
    	}
    	
        BasicPosition basicposition = basicPositionService.getById(aimpositionId);
        Long deliverid = user.getDeliverId();
        Long deptid = user.getDeptId();

        Set<Long> goodsIds = new HashSet<Long>();//存商品
        Map<Long, String> m1 = new HashMap<Long, String>();//存商品单价
        Map<Long, StorageStock> m3 = new HashMap<Long, StorageStock>();//库存id  对应源库存
        Map<Long, StorageStock> m4 = new HashMap<Long, StorageStock>();//商品id  对应源库存
        List<ExecuteNumberList> executeNumberList = new ArrayList<ExecuteNumberList>();
        for (int i = 0; i < _idlist.length; i++) {
        	ExecuteNumberList ExecuteNumberList = new ExecuteNumberList();
        	try {
            	ExecuteNumberList.setId(_idlist[i]);
            	ExecuteNumberList.setGoodsId(_glist[i]);
            	ExecuteNumberList.setExecuteNumber(_numlist[i]);
            	executeNumberList.add(ExecuteNumberList);
			} catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");
			}
		}
        for (ExecuteNumberList list : executeNumberList) {//更新源托盘的数量
            Long goodsId = list.getGoodsId();
            goodsIds.add(goodsId);
            BasicGoods basicGoods = basicGoodsService.getById(list.getGoodsId());//获取商品信息
            StorageStock ssr = storageStockService.getById(list.getId());

            if (ssr == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");
            }
            m3.put(list.getId(), ssr);
            String t = m1.get(goodsId);
            StorageStock hh = m4.get(goodsId);
            if (hh == null) {
                m4.put(goodsId, ssr);
            }
            if (t == null) {
                m1.put(goodsId, ssr.getUnitprice());
            }
            StorageStockParam ssp = new StorageStockParam();
            ssp.setId(ssr.getId());
            String executenumber = list.getExecuteNumber();
            if (executenumber == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("请输入移出数量");
            }
            BigDecimal b1 = new BigDecimal(executenumber);
            BigDecimal b2 = new BigDecimal(ssr.getNum());
            BigDecimal num = b2.subtract(b1);//计算移出后的数量
            BigDecimal ooo = new BigDecimal("0");
            if (num.compareTo(ooo) == -1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("移出数量超出");
            }
            String nums = num.toString();
            if (num.compareTo(ooo) == 0) {
				storageStockDetailedService.addNewDetailedstorageStock("移库", "", "移出", "目的地："+basicposition.getPositionNumber(), ssr,user);//新增 库存流水
                storageStockService.delete(ssp);
				try {
					StorageStockParam param2 = new StorageStockParam();
					param2.setTrayId(ssr.getTrayId());
					StorageStockResult storageStockResult = storageStockService.findBySpec(param2);
					if (storageStockResult == null) {
						BasicTrayParam basicTrayParam = new BasicTrayParam();
						basicTrayParam.setId(Integer.parseInt(ssr.getTrayId().toString()));
						basicTrayParam.setTrayState("闲置");
						basicTrayService.update(basicTrayParam);
					}
				} catch (Exception e) {
				}
            } else {
                BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
                BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume()); //体积
                BigDecimal u = new BigDecimal(ssr.getUnitprice());//单价

                BigDecimal sw = w.multiply(b1);//计算移出的质量
                BigDecimal sv = v.multiply(b1);//计算移出的体积
                BigDecimal su = u.multiply(b1);//计算移出的价格

                BigDecimal c2 = new BigDecimal(ssr.getStockWeight());
                BigDecimal ww = c2.subtract(sw);//计算移出后的质量

                BigDecimal d2 = new BigDecimal(ssr.getStockVolume());
                BigDecimal vv = d2.subtract(sv);//计算移出后的体积

                BigDecimal e2 = new BigDecimal(ssr.getStockMoney());
                BigDecimal uu = e2.subtract(su);//计算移出后的价格

                ssp.setNum(nums);
                ssp.setBalenum(nums);//新大包数
                ssp.setCanNum(nums);//新可用数量
                ssp.setStockWeight(ww.toString());//新重量
                ssp.setStockVolume(vv.toString());//新体积
                ssp.setStockMoney(uu.toString());//新金额
				storageStockDetailedService.addNewDetailedstorageStock("移库", "", "移出", "目的地："+basicposition.getPositionNumber()+",移出："+b1.toString(), ssr,user);//新增 库存流水
                storageStockService.update(ssp);//更新数量
            }
        }
        //商品信息
        if (goodsIds.isEmpty()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
            return ResponseData.error("数据错误");
        }
        for (Long goodsId : goodsIds) {//遍历商品
            BasicTrayResult basicTrayResult = addTray();//生成新托盘返回托盘id
            BasicGoods basicGoods = basicGoodsService.getById(goodsId);//获取商品信息
            if (basicGoods == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");

            }
            BigDecimal b1 = new BigDecimal("0");//商品总数量
            String unitprice = "0";
            for (int i = 0; i < executeNumberList.size(); i++) {//计算商品的总数量，及单价
                if (goodsId.equals(executeNumberList.get(i).getGoodsId())) {
                    String t = m1.get(goodsId);
                    if (t == null) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                        return ResponseData.error("数据错误");

                    } else {
                        unitprice = t;
                    }

                    BigDecimal b2 = new BigDecimal(executeNumberList.get(i).getExecuteNumber());
                    b1 = b2.add(b1);//计算存入库存表的商品总量

                }
            }
            StorageStockParam dd = new StorageStockParam();
            if (basicposition == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");

            }
            Integer areaid = basicposition.getPositionAreaId();//库区id
            BasicArea basicArea = basicAreaService.getById(areaid);
            if (basicArea == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");

            }
            Long warehouseId = basicArea.getAreaWarehouseId().longValue();
            String warehouseName = basicArea.getAreaWarehouseName();
            Long areaId = areaid.longValue();
            String areaNumber = basicposition.getAreaNumber();
            String positionNumber = basicposition.getPositionNumber();
            StorageStock sstockp = m4.get(goodsId);
            sstockp.setId(null);
            sstockp.setWarehouseId(warehouseId);//仓库id
            sstockp.setWarehouseName(warehouseName);//仓库编号
            sstockp.setAreaId(areaId);//库区id
            sstockp.setAreaNumber(areaNumber);//库区编号
            sstockp.setPositionId(aimpositionId);//库位id
            sstockp.setPositionNumber(positionNumber);//库区编好
            sstockp.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));//托盘id
            sstockp.setTrayNumber(basicTrayResult.getTrayNumber());//托盘编号
            sstockp.setDeptId(deptid);
            sstockp.setCreateUser(user.getUserId());
            BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
            BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume()); //体积
            BigDecimal u = new BigDecimal(unitprice);//单价
            sstockp.setNum(b1.toString());//新数量
            sstockp.setBalenum(b1.toString());//新大包数
            sstockp.setCanNum(b1.toString());//新可用数量
            sstockp.setStockWeight(b1.multiply(w).toString());//新重量
            sstockp.setStockVolume(b1.multiply(v).toString());//新体积
            sstockp.setStockMoney(String.valueOf(b1.multiply(u).toString()));//新金额
            sstockp.setDeliverId(deliverid);//交付id
            sstockp.setDeptId(deptid);//部门id
            ToolUtil.copyProperties(sstockp, dd);
            storageStockService.add(dd);//添加新托盘生成库存
            StorageStockResult result = storageStockService.findBySpec2(dd);
			storageStockDetailedService.addNewDetailedResult("移库", "", "移入新托", "移入新托："+b1.toString(), result,user);//新增 库存流水
            for (int i = 0; i < executeNumberList.size(); i++) {//生成新记录
                if (goodsId.equals(executeNumberList.get(i).getGoodsId())) {
                    MovingPalletsmergeParam movingPalletsmergeParam = new MovingPalletsmergeParam();
                    StorageStock ssr = m3.get(executeNumberList.get(i).getId());
                    if (ssr == null) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                        return ResponseData.error("数据错误");
                    }
                    movingPalletsmergeParam.setSourcewarehouseId(ssr.getWarehouseId());
                    movingPalletsmergeParam.setSourcewarehouseName(ssr.getWarehouseName());
                    movingPalletsmergeParam.setSourcepositionId(ssr.getPositionId());
                    movingPalletsmergeParam.setSourcepositionNumber(ssr.getPositionNumber());
                    movingPalletsmergeParam.setSourceareaId(ssr.getAreaId());
                    movingPalletsmergeParam.setSourceareaNumber(ssr.getAreaNumber());
                    movingPalletsmergeParam.setSourcenum(executeNumberList.get(i).getExecuteNumber());
                    movingPalletsmergeParam.setSourcetrayId(ssr.getTrayId());
                    movingPalletsmergeParam.setSourcetrayNumber(ssr.getTrayNumber());

                    movingPalletsmergeParam.setGoodsId(ssr.getGoodsId());
                    movingPalletsmergeParam.setGoodsName(ssr.getGoodsName());
                    movingPalletsmergeParam.setGoodsNumber(ssr.getGoodsNumber());
                    BasicGoods basicGoodsff = basicGoodsService.getById(ssr.getGoodsId());
                    movingPalletsmergeParam.setGoodsNo(basicGoodsff.getGoodsNo());

                    movingPalletsmergeParam.setAimwarehouseId(warehouseId);
                    movingPalletsmergeParam.setAimwarehouseName(warehouseName);
                    movingPalletsmergeParam.setAimpositionId(aimpositionId);
                    movingPalletsmergeParam.setAimpositionNumber(positionNumber);
                    movingPalletsmergeParam.setAimareaId(areaId);
                    movingPalletsmergeParam.setAimareaNumber(areaNumber);
                    movingPalletsmergeParam.setAimnum(executeNumberList.get(i).getExecuteNumber());
                    movingPalletsmergeParam.setAimtrayId(Long.parseLong(basicTrayResult.getId().toString()));
                    movingPalletsmergeParam.setAimtrayNumber(basicTrayResult.getTrayNumber());
                    movingPalletsmergeParam.setDeliverId(deliverid);
                    movingPalletsmergeParam.setDeptId(deptid);
                    movingPalletsmergeParam.setTypr("移入新托");
                    movingPalletsmergeParam.setNodes(user.getName());
                    movingPalletsmergeService.add(movingPalletsmergeParam);//添加记录
                }
            }
        }
        return ResponseData.success();
    }

    /**
     * 移库功能(添加新托盘)
     * @return sourcepositionId 源
     * aimpositionId 目的地库位id
     */
    @RequestMapping("/executenew")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData executenew(Long[] _idlist,String[] _numlist, Long aimpositionId,String aimpositionNumber) {
    	User user = userAop.getUser();
    	if(ToolUtil.isEmpty(aimpositionId)) {
    		if(ToolUtil.isNotEmpty(aimpositionNumber)) {
    			BasicPositionParam basicPositionParam = new BasicPositionParam();
    			basicPositionParam.setPositionNumber(aimpositionNumber);
    			basicPositionParam.setDeliverId(user.getDeliverId());
    			BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(),user.getOperateId());
    			if(basicPositionResult == null) {
    				return ResponseData.error("目的库位不存在！");
    			} else {
    				aimpositionId = Long.parseLong(basicPositionResult.getId().toString());
    			}
    		} else {
				return ResponseData.error("请选择目的库位！");
    		}
    	}
        BasicPosition basicposition = basicPositionService.getById(aimpositionId);

        List<ExecuteNumberList> executeNumberList = new ArrayList<ExecuteNumberList>();
        for (int i = 0; i < _idlist.length; i++) {
        	ExecuteNumberList ExecuteNumberList = new ExecuteNumberList();
        	try {
            	ExecuteNumberList.setId(_idlist[i]);
            	ExecuteNumberList.setExecuteNumber(_numlist[i]);
            	executeNumberList.add(ExecuteNumberList);
			} catch (Exception e) {
                return ResponseData.error("数据错误");
			}
		}

        List<StorageStockParam> adds = new ArrayList<StorageStockParam>();//要新增的库存
        
        for (ExecuteNumberList list : executeNumberList) {//更新源托盘的数量
            StorageStock ssr = storageStockService.getById(list.getId());
            if (ssr == null) {
                return ResponseData.error("源数据不存在");
            }
        	boolean addsyou = false;
        	for (StorageStockParam addsp : adds) {
				if(addsp.getGoodsId().equals(ssr.getGoodsId())&&addsp.getGoodsbatchs().equals(ssr.getGoodsbatchs())) {
					BigDecimal executeNumber = new BigDecimal(list.getExecuteNumber());//移出数
					BigDecimal num = new BigDecimal(addsp.getNum());
					BigDecimal newnum = num.add(executeNumber).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					addsp.setNum(newnum.toString());
					addsyou = true;
					break;
				}
			}
        	if (!addsyou) {
        		StorageStockParam add = new StorageStockParam();
        		ToolUtil.copyProperties(ssr, add);
        		add.setSource(ssr);
        		add.setNum(list.getExecuteNumber());
        		adds.add(add);
			}
        	
            BasicGoods basicGoods = basicGoodsService.getById(ssr.getGoodsId());//获取商品信息
            StorageStockParam ssp = new StorageStockParam();
            ssp.setId(ssr.getId());
            String executenumber = list.getExecuteNumber();
            if (executenumber == null) {
                return ResponseData.error("请输入移出数量");
            }
            BigDecimal b1 = new BigDecimal(executenumber);
            BigDecimal b2 = new BigDecimal(ssr.getNum());
            BigDecimal num = b2.subtract(b1).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的数量
            BigDecimal ooo = new BigDecimal("0");
            if (num.compareTo(ooo) == -1) {
                return ResponseData.error("移出数量超出");
            }
            String nums = num.toString();

            if (num.compareTo(ooo) == 0) {
				storageStockDetailedService.addNewDetailedstorageStock("移库", "", "移出", "目的地："+basicposition.getPositionNumber(), ssr,user);//新增 库存流水
                storageStockService.delete(ssp);
				try {
					StorageStockParam param2 = new StorageStockParam();
					param2.setTrayId(ssr.getTrayId());
					StorageStockResult storageStockResult = storageStockService.findBySpec(param2);
					if (storageStockResult == null) {
						BasicTrayParam basicTrayParam = new BasicTrayParam();
						basicTrayParam.setId(Integer.parseInt(ssr.getTrayId().toString()));
						basicTrayParam.setTrayState("闲置");
						basicTrayService.update(basicTrayParam);
					}
				} catch (Exception e) {
				}
            } else {
                BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
                BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume()); //体积
                BigDecimal u = new BigDecimal(ssr.getUnitprice());//单价
                BigDecimal ww = w.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的重量
                BigDecimal vv = v.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的体积
                BigDecimal uu = u.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的价格

                ssp.setNum(nums);
                ssp.setBalenum(nums);//新大包数
                ssp.setCanNum(nums);//新可用数量
                ssp.setUnitprice(u.toString());
                ssp.setStockWeight(ww.toString());//新重量
                ssp.setStockVolume(vv.toString());//新体积
                ssp.setStockMoney(uu.toString());//新金额
				storageStockDetailedService.addNewDetailedstorageStock("移库", "", "移出", "目的地："+basicposition.getPositionNumber()+",移出："+b1.toString(), ssr,user);//新增 库存流水
                storageStockService.update(ssp);//更新数量
            }
        }
    	
    	for (StorageStockParam addsp : adds) {
    		StorageStock source = addsp.getSource();
            BasicTrayResult basicTrayResult = addTray();//生成新托盘返回托盘id
            BasicGoods basicGoods = basicGoodsService.getById(addsp.getGoodsId());//获取商品信息
            if (basicGoods == null) {
                return ResponseData.error("数据错误");
            }
            BigDecimal b1 = new BigDecimal(addsp.getNum());//商品总数量
            if (basicposition == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");

            }
            Integer areaid = basicposition.getPositionAreaId();//库区id
            BasicArea basicArea = basicAreaService.getById(areaid);
            if (basicArea == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");

            }
            Long warehouseId = basicArea.getAreaWarehouseId().longValue();
            String warehouseName = basicArea.getAreaWarehouseName();
            Long areaId = areaid.longValue();
            String areaNumber = basicposition.getAreaNumber();
            String positionNumber = basicposition.getPositionNumber();
            addsp.setId(null);
            addsp.setWarehouseId(warehouseId);//仓库id
            addsp.setWarehouseName(warehouseName);//仓库编号
            addsp.setAreaId(areaId);//库区id
            addsp.setAreaNumber(areaNumber);//库区编号
            addsp.setPositionId(aimpositionId);//库位id
            addsp.setPositionNumber(positionNumber);//库区编好
            addsp.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));//托盘id
            addsp.setTrayNumber(basicTrayResult.getTrayNumber());//托盘编号
            addsp.setDeptId(user.getDeptId());
            BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
            BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume()); //体积
            BigDecimal u = new BigDecimal(basicGoods.getGoodsCharging());//单价
            addsp.setNum(b1.toString());//新数量
            addsp.setBalenum(b1.toString());//新大包数
            addsp.setCanNum(b1.toString());//新可用数量
            addsp.setStockWeight(b1.multiply(w).toString());//新重量
            addsp.setStockVolume(b1.multiply(v).toString());//新体积
            addsp.setStockMoney(String.valueOf(b1.multiply(u).toString()));//新金额
            addsp.setDeliverId(user.getDeliverId());//交付id


            //是否储位限品
            BasicCustomer basicCustomer = basicCustomerService.getById(source.getCustomerId());
            if(ToolUtil.isNotEmpty(basicCustomer.getStorageLimitFlag()) && basicCustomer.getStorageLimitFlag().equals("是")) {
                ResponseData responseData = storageStockService.storageLimitItems(user, basicposition.getPositionNumber(), warehouseId, basicGoods.getGoodsNo(),basicGoods.getGoodsNumber(),source.getGoodsbatchs());
                if(responseData.getCode() == 500) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                    return responseData;
                }
            }


            storageStockService.addReturnId(addsp);//添加新托盘生成库存
			storageStockDetailedService.addNewDetailed("移库", "", "移入新托", "移入新托："+b1.toString(), addsp,user);//新增 库存流水

            MovingPalletsmergeParam movingPalletsmergeParam = new MovingPalletsmergeParam();
            movingPalletsmergeParam.setSourcewarehouseId(source.getWarehouseId());
            movingPalletsmergeParam.setSourcewarehouseName(source.getWarehouseName());
            movingPalletsmergeParam.setSourcepositionId(source.getPositionId());
            movingPalletsmergeParam.setSourcepositionNumber(source.getPositionNumber());
            movingPalletsmergeParam.setSourceareaId(source.getAreaId());
            movingPalletsmergeParam.setSourceareaNumber(source.getAreaNumber());
            movingPalletsmergeParam.setSourcenum(addsp.getNum());
            movingPalletsmergeParam.setSourcetrayId(source.getTrayId());
            movingPalletsmergeParam.setSourcetrayNumber(source.getTrayNumber());

            movingPalletsmergeParam.setGoodsId(source.getGoodsId());
            movingPalletsmergeParam.setGoodsName(source.getGoodsName());
            movingPalletsmergeParam.setGoodsNumber(source.getGoodsNumber());
            movingPalletsmergeParam.setGoodsNo(basicGoods.getGoodsNo());

            movingPalletsmergeParam.setAimwarehouseId(warehouseId);
            movingPalletsmergeParam.setAimwarehouseName(warehouseName);
            movingPalletsmergeParam.setAimpositionId(aimpositionId);
            movingPalletsmergeParam.setAimpositionNumber(positionNumber);
            movingPalletsmergeParam.setAimareaId(areaId);
            movingPalletsmergeParam.setAimareaNumber(areaNumber);
            movingPalletsmergeParam.setAimnum(addsp.getNum());
            movingPalletsmergeParam.setAimtrayId(Long.parseLong(basicTrayResult.getId().toString()));
            movingPalletsmergeParam.setAimtrayNumber(basicTrayResult.getTrayNumber());
            movingPalletsmergeParam.setDeliverId(user.getDeliverId());
            movingPalletsmergeParam.setDeptId(user.getDeptId());
            movingPalletsmergeParam.setTypr("移入新托");
            movingPalletsmergeParam.setNodes(user.getName());
            movingPalletsmergeService.add(movingPalletsmergeParam);//添加记录
		}
		return ResponseData.success();
    }

    /**
     * 合托功能(不添加新托盘)
     * @return sourcepositionId 源
     * aimid 目的托盘库位id
     */
    @RequestMapping("/executenonew2")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData executenonew2(Long[] _idlist,String[] _numlist, Long aimid) {
    	User user = userAop.getUser();
        StorageStock aimStorageStock = storageStockService.getById(aimid);//目的库存信息
        List<ExecuteNumberList> executeNumberList = new ArrayList<ExecuteNumberList>();
        for (int i = 0; i < _idlist.length; i++) {
        	ExecuteNumberList ExecuteNumberList = new ExecuteNumberList();
        	try {
            	ExecuteNumberList.setId(_idlist[i]);
            	ExecuteNumberList.setExecuteNumber(_numlist[i]);
            	executeNumberList.add(ExecuteNumberList);
			} catch (Exception e) {
                return ResponseData.error("数据错误");
			}
		}

        List<StorageStockParam> adds = new ArrayList<StorageStockParam>();//要新增的库存
        
        for (ExecuteNumberList list : executeNumberList) {//更新源托盘的数量
            StorageStock ssr = storageStockService.getById(list.getId());
            if (ssr == null) {
                return ResponseData.error("源数据不存在");
            }
        	boolean addsyou = false;
        	for (StorageStockParam addsp : adds) {
				if(addsp.getGoodsId().equals(ssr.getGoodsId())&&addsp.getGoodsbatchs().equals(ssr.getGoodsbatchs())) {
					BigDecimal executeNumber = new BigDecimal(list.getExecuteNumber());//移出数
					BigDecimal num = new BigDecimal(addsp.getNum());
					BigDecimal newnum = num.add(executeNumber).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					addsp.setNum(newnum.toString());
					addsyou = true;
					break;
				}
			}
        	if (!addsyou) {
        		StorageStockParam add = new StorageStockParam();
        		ToolUtil.copyProperties(ssr, add);
        		add.setNum(list.getExecuteNumber());
        		adds.add(add);
			}
        	
            BasicGoods basicGoods = basicGoodsService.getById(ssr.getGoodsId());//获取商品信息
            StorageStockParam ssp = new StorageStockParam();
            ssp.setId(ssr.getId());
            String executenumber = list.getExecuteNumber();
            if (executenumber == null) {
                return ResponseData.error("请输入移出数量");
            }
            BigDecimal b1 = new BigDecimal(executenumber);
            BigDecimal b2 = new BigDecimal(ssr.getNum());
            BigDecimal num = b2.subtract(b1).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的数量
            BigDecimal ooo = new BigDecimal("0");
            if (num.compareTo(ooo) == -1) {
                return ResponseData.error("移出数量超出");
            }
            String nums = num.toString();
            if (num.compareTo(ooo) == 0) {
				storageStockDetailedService.addNewDetailedstorageStock("合托", "", "移出", "目的地："+aimStorageStock.getPositionNumber(), ssr,user);//新增 库存流水
                storageStockService.delete(ssp);
				try {
					StorageStockParam param2 = new StorageStockParam();
					param2.setTrayId(ssr.getTrayId());
					StorageStockResult storageStockResult = storageStockService.findBySpec(param2);
					if (storageStockResult == null) {
						BasicTrayParam basicTrayParam = new BasicTrayParam();
						basicTrayParam.setId(Integer.parseInt(ssr.getTrayId().toString()));
						basicTrayParam.setTrayState("闲置");
						basicTrayService.update(basicTrayParam);
					}
				} catch (Exception e) {
				}
            } else {
                BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
                BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume()); //体积
                BigDecimal u = new BigDecimal(ssr.getUnitprice());//单价
                BigDecimal ww = w.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的重量
                BigDecimal vv = v.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的体积
                BigDecimal uu = u.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的价格

                ssp.setNum(nums);
                ssp.setBalenum(nums);//新大包数
                ssp.setCanNum(nums);//新可用数量
                ssp.setUnitprice(u.toString());
                ssp.setStockWeight(ww.toString());//新重量
                ssp.setStockVolume(vv.toString());//新体积
                ssp.setStockMoney(uu.toString());//新金额
				storageStockDetailedService.addNewDetailedstorageStock("合托", "", "移出", "目的地："+aimStorageStock.getPositionNumber()+",移出："+b1.toString(), ssr,user);//新增 库存流水
                storageStockService.update(ssp);//更新数量
            }
            //生成移库合托记录
            MovingPalletsmergeParam movingPalletsmergeParam = new MovingPalletsmergeParam();
            //源
            movingPalletsmergeParam.setSourcewarehouseId(ssr.getWarehouseId());
            movingPalletsmergeParam.setSourcewarehouseName(ssr.getWarehouseName());
            movingPalletsmergeParam.setSourcepositionId(ssr.getPositionId());
            movingPalletsmergeParam.setSourcepositionNumber(ssr.getPositionNumber());
            movingPalletsmergeParam.setSourceareaId(ssr.getAreaId());
            movingPalletsmergeParam.setSourceareaNumber(ssr.getAreaNumber());
            movingPalletsmergeParam.setSourcenum(list.getExecuteNumber());
            movingPalletsmergeParam.setSourcetrayId(ssr.getTrayId());
            movingPalletsmergeParam.setSourcetrayNumber(ssr.getTrayNumber());
            //商品
            movingPalletsmergeParam.setGoodsId(ssr.getGoodsId());
            movingPalletsmergeParam.setGoodsName(ssr.getGoodsName());
            movingPalletsmergeParam.setGoodsNumber(ssr.getGoodsNumber());
            BasicGoods basicGoodsff = basicGoodsService.getById(ssr.getGoodsId());
            movingPalletsmergeParam.setGoodsNo(basicGoodsff.getGoodsNo());
            //目的
            movingPalletsmergeParam.setAimwarehouseId(aimStorageStock.getWarehouseId());
            movingPalletsmergeParam.setAimwarehouseName(aimStorageStock.getWarehouseName());
            movingPalletsmergeParam.setAimpositionId(aimStorageStock.getPositionId());
            movingPalletsmergeParam.setAimpositionNumber(aimStorageStock.getPositionNumber());
            movingPalletsmergeParam.setAimareaId(aimStorageStock.getAreaId());
            movingPalletsmergeParam.setAimareaNumber(aimStorageStock.getAreaNumber());
            movingPalletsmergeParam.setAimnum(list.getExecuteNumber());
            movingPalletsmergeParam.setAimtrayId(aimStorageStock.getTrayId());
            movingPalletsmergeParam.setAimtrayNumber(aimStorageStock.getTrayNumber());
            movingPalletsmergeParam.setDeliverId(user.getDeliverId());
            movingPalletsmergeParam.setDeptId(user.getDeptId());
            movingPalletsmergeParam.setTypr("合托");
            movingPalletsmergeParam.setNodes(user.getName());
            movingPalletsmergeService.add(movingPalletsmergeParam);//添加记录
        }

    	for (StorageStockParam addsp : adds) {
            BasicGoods basicGoods = basicGoodsService.getById(addsp.getGoodsId());//获取商品信息
            BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
            BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());//体积
            BigDecimal u = new BigDecimal(basicGoods.getGoodsCharging());//单价
            BigDecimal b1 = new BigDecimal(addsp.getNum());//商品总数量
            StorageStockParam aimStorageStockParamA = new StorageStockParam();
            ToolUtil.copyProperties(aimStorageStock, aimStorageStockParamA);//目的转化
    		if(addsp.getGoodsId().equals(aimStorageStock.getGoodsId()) && addsp.getGoodsbatchs().equals(aimStorageStock.getGoodsbatchs())) {//商品和批次相同，进行合并
                BigDecimal oldn1 = new BigDecimal(aimStorageStock.getNum());
                //增加后的量
                BigDecimal zjn1 = oldn1.add(b1).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                BigDecimal zjw1 = zjn1.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                BigDecimal zjv1 = zjn1.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                BigDecimal zjm1 = zjn1.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                aimStorageStockParamA.setNum(zjn1.toString());//新数量
                aimStorageStockParamA.setBalenum(zjn1.toString());//新大包数
                aimStorageStockParamA.setCanNum(zjn1.toString());//新可用数量
                aimStorageStockParamA.setStockWeight(zjw1.toString());//新重量
                aimStorageStockParamA.setStockVolume(zjv1.toString());//新体积
                aimStorageStockParamA.setStockMoney(zjm1.toString());//新金额
                aimStorageStockParamA.setUnitprice(u.toString());
                aimStorageStockParamA.setDeliverId(user.getDeliverId());//交付id
                aimStorageStockParamA.setDeptId(user.getDeptId());//部门id
                storageStockService.update(aimStorageStockParamA);
                try {
    				storageStockDetailedService.addNewDetailed("合托", "", "移入", "移入："+b1.toString(), aimStorageStockParamA,user);//新增 库存流水
				} catch (Exception e) {
				}
    		} else {//生成相同托盘的库存
    			aimStorageStockParamA.setNum(b1.toString());//新数量
    			aimStorageStockParamA.setBalenum(b1.toString());//新大包数
    			aimStorageStockParamA.setCanNum(b1.toString());//新可用数量
    			aimStorageStockParamA.setStockWeight(b1.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//新重量
    			aimStorageStockParamA.setStockVolume(b1.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//新体积
    			aimStorageStockParamA.setStockMoney(b1.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//新金额
    			aimStorageStockParamA.setId(null);
    			aimStorageStockParamA.setGoodsId(addsp.getGoodsId());
    			aimStorageStockParamA.setGoodsName(basicGoods.getGoodsName());
    			aimStorageStockParamA.setGoodsNumber(basicGoods.getGoodsNumber());
    			aimStorageStockParamA.setGoodsbatchs(addsp.getGoodsbatchs());
    			aimStorageStockParamA.setProducetime(addsp.getProducetime());


                //是否储位限品
                BasicCustomer basicCustomer = basicCustomerService.getById(aimStorageStock.getCustomerId());
                if(ToolUtil.isNotEmpty(basicCustomer.getStorageLimitFlag()) && basicCustomer.getStorageLimitFlag().equals("是")) {
                    ResponseData responseData = storageStockService.storageLimitItems(user, aimStorageStock.getPositionNumber(), aimStorageStock.getWarehouseId(), basicGoods.getGoodsNo(),basicGoods.getGoodsNumber(),aimStorageStock.getGoodsbatchs());
                    if(responseData.getCode() == 500) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                        return responseData;
                    }
                }


                storageStockService.addReturnId(aimStorageStockParamA);
                try {
    				storageStockDetailedService.addNewDetailed("合托", "", "移入", "移入："+b1.toString(), aimStorageStockParamA,user);//新增 库存流水
				} catch (Exception e) {
				}
    		}
		}
		return ResponseData.success();
    }

    /**
     * 合托功能(不添加新托盘)
     * @return sourcepositionId 源
     * aimid 目的托盘库位id
     */
    @RequestMapping("/executenonew")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData executenonew(Long[] _idlist,Long[] _glist,String[] _numlist, Long aimid) {
    	User user = userAop.getUser();
        StorageStock aimStorageStock = storageStockService.getById(aimid);//目的库存信息
        Long deliverid = user.getDeliverId();
        Long deptid = user.getDeptId();
        Long userid = user.getUserId();
        String goodsbatchs = DateUtil.getDate();//按照最后一个批次进行计算
        Map<Long, String> map = new HashMap<Long, String>();//存商品单价  <商品ID，单价>
        StorageStockParam sourceStorageStockParam = new StorageStockParam();
        StorageStockParam aimStorageStockParam = new StorageStockParam();
        StorageStockParam aimStorageStockParams = new StorageStockParam();
        StorageStockParam aimStorageStockParamA = new StorageStockParam();
        List<ExecuteNumberList> executeNumberList = new ArrayList<ExecuteNumberList>();
        for (int i = 0; i < _idlist.length; i++) {
        	ExecuteNumberList ExecuteNumberList = new ExecuteNumberList();
        	try {
            	ExecuteNumberList.setId(_idlist[i]);
            	ExecuteNumberList.setGoodsId(_glist[i]);
            	ExecuteNumberList.setExecuteNumber(_numlist[i]);
            	executeNumberList.add(ExecuteNumberList);
			} catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");
			}
		}
        for (ExecuteNumberList list : executeNumberList) {//更新源托盘的数量
            StorageStock sourceStorageStock = storageStockService.getById(list.getId());//源
            goodsbatchs=sourceStorageStock.getGoodsbatchs();//按照最后一个批次进行计算
            ToolUtil.copyProperties(sourceStorageStock, sourceStorageStockParam);//源转化
            ToolUtil.copyProperties(aimStorageStock, aimStorageStockParam);//目的转化
            Long goodsId = list.getGoodsId();
            String t = map.get(goodsId);
            BasicGoods basicGoods = basicGoodsService.getById(list.getGoodsId());//获取商品信息

            boolean sss=(!sourceStorageStock.getTrayNumber().equals(aimStorageStock.getTrayNumber()));//不同托盘
            boolean ppp = (sourceStorageStock.getGoodsbatchs().equals(aimStorageStock.getGoodsbatchs()));//同批次
            boolean www=(!aimid.equals(list.getId()));///不同库位
            if(www && ppp){//移入不同库位//移入相同库存内无需变化只生成记录即可
                if (t == null) {
                    map.put(goodsId, list.getExecuteNumber());
                } else {
                    BigDecimal b1 = new BigDecimal(t);
                    BigDecimal b2 = new BigDecimal(list.getExecuteNumber());//源数量
                    BigDecimal num = b2.add(b1);//计算总量
                    map.put(goodsId, num.toString());
                }
                String executenumber = list.getExecuteNumber();//移除数量
                BigDecimal b1 = new BigDecimal(executenumber);
                BigDecimal b2 = new BigDecimal(sourceStorageStock.getNum());//源数量
                BigDecimal num = b2.subtract(b1);//计算移出后的数量
                String nums = num.toString();
                BigDecimal ooo = new BigDecimal("0");
                if (num.compareTo(ooo) == -1) {//移出数量大于原数量
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                    return ResponseData.error("移出数量不得大于原数量");
                } else if (num.compareTo(ooo) == 0) {
    				storageStockDetailedService.addNewDetailed("合托", "", "移出", "目的地："+aimStorageStock.getPositionNumber(), sourceStorageStockParam,user);//新增 库存流水
                    storageStockService.delete(sourceStorageStockParam);//直接删除原库存
                    if(sss){
                    	try {
                    		StorageStockParam param2 = new StorageStockParam();
                    		param2.setTrayId(sourceStorageStockParam.getTrayId());
                    		StorageStockResult storageStockResult = storageStockService.findBySpec(param2);
                    		if (storageStockResult == null) {
                    			BasicTrayParam basicTrayParam = new BasicTrayParam();
                    			basicTrayParam.setId(Integer.parseInt(sourceStorageStockParam.getTrayId().toString()));
                    			basicTrayParam.setTrayState("闲置");
                    			basicTrayService.update(basicTrayParam);
                    		}
                    	} catch (Exception e) {
                    	}
                    }
                } else {
                    BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
                    BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume()); //体积
                    BigDecimal u = new BigDecimal(sourceStorageStockParam.getUnitprice());//单价
                    BigDecimal sw = w.multiply(b1);//计算移出的质量
                    BigDecimal sv = v.multiply(b1);//计算移出的体积
                    BigDecimal su = u.multiply(b1);//计算移出的价格
                    BigDecimal c2 = new BigDecimal(sourceStorageStockParam.getStockWeight());
                    BigDecimal ww = c2.subtract(sw).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的质量
                    BigDecimal d2 = new BigDecimal(sourceStorageStockParam.getStockVolume());
                    BigDecimal vv = d2.subtract(sv).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的体积
                    BigDecimal e2 = new BigDecimal(sourceStorageStockParam.getStockMoney());
                    BigDecimal uu = e2.subtract(su).setScale(3, BigDecimal.ROUND_HALF_DOWN);//计算移出后的价格
                    sourceStorageStockParam.setNum(nums);
                    sourceStorageStockParam.setBalenum(nums);//新大包数
                    sourceStorageStockParam.setCanNum(nums);//新可用数量
                    sourceStorageStockParam.setStockWeight(ww.toString());//新重量
                    sourceStorageStockParam.setStockVolume(vv.toString());//新体积
                    sourceStorageStockParam.setStockMoney(uu.toString());//新金额
                    sourceStorageStockParam.setDeptId(deptid);
                    sourceStorageStockParam.setDeliverId(deliverid);
                    sourceStorageStockParam.setUpdateUser(userid);
    				storageStockDetailedService.addNewDetailed("合托", "", "移出", "目的地："+aimStorageStock.getPositionNumber()+",移出："+b1.toString(), sourceStorageStockParam,user);//新增 库存流水
                    storageStockService.update(sourceStorageStockParam);//移除后更新源数量
                }
            }
            //生成移库合托记录
            MovingPalletsmergeParam movingPalletsmergeParam = new MovingPalletsmergeParam();
            //源
            movingPalletsmergeParam.setSourcewarehouseId(sourceStorageStock.getWarehouseId());
            movingPalletsmergeParam.setSourcewarehouseName(sourceStorageStock.getWarehouseName());
            movingPalletsmergeParam.setSourcepositionId(sourceStorageStock.getPositionId());
            movingPalletsmergeParam.setSourcepositionNumber(sourceStorageStock.getPositionNumber());
            movingPalletsmergeParam.setSourceareaId(sourceStorageStock.getAreaId());
            movingPalletsmergeParam.setSourceareaNumber(sourceStorageStock.getAreaNumber());
            movingPalletsmergeParam.setSourcenum(list.getExecuteNumber());
            movingPalletsmergeParam.setSourcetrayId(sourceStorageStock.getTrayId());
            movingPalletsmergeParam.setSourcetrayNumber(sourceStorageStock.getTrayNumber());
            //商品
            movingPalletsmergeParam.setGoodsId(sourceStorageStock.getGoodsId());
            movingPalletsmergeParam.setGoodsName(sourceStorageStock.getGoodsName());
            movingPalletsmergeParam.setGoodsNumber(sourceStorageStock.getGoodsNumber());
            BasicGoods basicGoodsff = basicGoodsService.getById(sourceStorageStock.getGoodsId());
            movingPalletsmergeParam.setGoodsNo(basicGoodsff.getGoodsNo());
            //目的
            movingPalletsmergeParam.setAimwarehouseId(aimStorageStock.getWarehouseId());
            movingPalletsmergeParam.setAimwarehouseName(aimStorageStock.getWarehouseName());
            movingPalletsmergeParam.setAimpositionId(aimStorageStock.getPositionId());
            movingPalletsmergeParam.setAimpositionNumber(aimStorageStock.getPositionNumber());
            movingPalletsmergeParam.setAimareaId(aimStorageStock.getAreaId());
            movingPalletsmergeParam.setAimareaNumber(aimStorageStock.getAreaNumber());
            movingPalletsmergeParam.setAimnum(list.getExecuteNumber());
            movingPalletsmergeParam.setAimtrayId(aimStorageStock.getTrayId());
            movingPalletsmergeParam.setAimtrayNumber(aimStorageStock.getTrayNumber());
            movingPalletsmergeParam.setDeliverId(deliverid);
            movingPalletsmergeParam.setDeptId(deptid);
            movingPalletsmergeParam.setTypr("合托");
            movingPalletsmergeParam.setNodes(user.getName());
            movingPalletsmergeService.add(movingPalletsmergeParam);//添加记录
        }

        for (Map.Entry<Long, String> entry : map.entrySet()) {
            ToolUtil.copyProperties(aimStorageStock, aimStorageStockParam);//目的转化
            ToolUtil.copyProperties(aimStorageStock, aimStorageStockParams);//目的转化
            aimStorageStockParams.setGoodsId(entry.getKey());
            StorageStockResult sdd=storageStockService.findByTrayId(aimStorageStockParams);//通过托盘ID和 商品ID 查询商品托盘信息
            BasicGoods basicGoods = basicGoodsService.getById(entry.getKey());//获取商品信息
            if (basicGoods == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("数据错误");
            }
            BigDecimal b1 = new BigDecimal(entry.getValue());//商品增加总数量
            BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
            BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());//体积
            BigDecimal u = new BigDecimal(basicGoods.getGoodsCharging());//单价
            BigDecimal oldn = new BigDecimal(aimStorageStock.getNum());//原数量
            BigDecimal oldc = new BigDecimal(aimStorageStock.getCanNum());//原数量
            BigDecimal oldV = new BigDecimal( aimStorageStock.getStockVolume());//原体积
            BigDecimal oldw = new BigDecimal( aimStorageStock.getStockWeight());//原重量
            BigDecimal oldm = new BigDecimal( aimStorageStock.getStockMoney());//原金额
            //增加后的量
            String zjn=(oldn.add(b1).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
            String zjc=(oldc.add(b1).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
            String zjw=(oldw.add(b1.multiply(w)).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
            String zjv=(oldV.add(b1.multiply(v)).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
            String zjm=(oldm.add(b1.multiply(u)).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
            aimStorageStockParam.setNum(zjn);//新数量
            aimStorageStockParam.setBalenum(zjn);//新大包数
            aimStorageStockParam.setCanNum(zjc);//新可用数量
            aimStorageStockParam.setStockWeight(zjw);//新重量
            aimStorageStockParam.setStockVolume(zjv);//新体积
            aimStorageStockParam.setStockMoney(zjm);//新金额
            aimStorageStockParam.setUpdateUser(user.getUserId());
            aimStorageStockParam.setDeliverId(deliverid);//交付id
            aimStorageStockParam.setDeptId(deptid);//部门id
            if(entry.getKey().equals(aimStorageStock.getGoodsId())){//托盘上的商品相同
				storageStockDetailedService.addNewDetailed("合托", "", "移入", "移入："+b1.toString(), aimStorageStockParam,user);//新增 库存流水
                storageStockService.update(aimStorageStockParam);
            }else {//不是一种商品
                if( StringUtils.isEmpty(sdd)){//该托盘上没有这个商品，则添加一相同托盘
                    aimStorageStockParam.setNum(b1.toString());//新数量
                    aimStorageStockParam.setBalenum(b1.toString());//新大包数
                    aimStorageStockParam.setCanNum(b1.toString());//新可用数量
                    aimStorageStockParam.setStockWeight(b1.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//新重量
                    aimStorageStockParam.setStockVolume(b1.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//新体积
                    aimStorageStockParam.setStockMoney(b1.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//新金额
                    aimStorageStockParam.setId(null);
                    aimStorageStockParam.setGoodsId(entry.getKey());
                    aimStorageStockParam.setGoodsName(basicGoods.getGoodsName());
                    aimStorageStockParam.setGoodsNumber(basicGoods.getGoodsNumber());
                    aimStorageStockParam.setGoodsbatchs(goodsbatchs);//按照最后一个批次进行计算
                    storageStockService.add(aimStorageStockParam);
                    try {
                        StorageStockResult result = storageStockService.findBySpec2(aimStorageStockParam);
        				storageStockDetailedService.addNewDetailedResult("合托", "", "移入", "移入："+b1.toString(), result,user);//新增 库存流水
					} catch (Exception e) {
					}
                }else {//该托盘上有相同货物，则更新到相应库存
                    ToolUtil.copyProperties(sdd, aimStorageStockParamA);//目的转化
                    //storageStockService.getById(sdd.getId());
                    BigDecimal oldn1 = new BigDecimal(aimStorageStockParamA.getNum());
                    BigDecimal oldc1 = new BigDecimal(aimStorageStockParamA.getCanNum());
                    BigDecimal oldV1 = new BigDecimal( aimStorageStockParamA.getStockVolume());
                    BigDecimal oldw1 = new BigDecimal( aimStorageStockParamA.getStockWeight());
                    BigDecimal oldm1 = new BigDecimal( aimStorageStockParamA.getStockMoney());
                    //增加后的量
                    String zjn1=(oldn1.add(b1).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
                    String zjc1=(oldc1.add(b1).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
                    String zjw1=(oldw1.add(b1.multiply(w)).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
                    String zjv1=(oldV1.add(b1.multiply(v)).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
                    String zjm1=(oldm1.add(b1.multiply(u)).setScale(3, BigDecimal.ROUND_HALF_DOWN)).toString();
                    aimStorageStockParamA.setNum(zjn1);//新数量
                    aimStorageStockParamA.setBalenum(zjn1);//新大包数
                    aimStorageStockParamA.setCanNum(zjc1);//新可用数量
                    aimStorageStockParamA.setStockWeight(zjw1);//新重量
                    aimStorageStockParamA.setStockVolume(zjv1);//新体积
                    aimStorageStockParamA.setStockMoney(zjm1);//新金额
                    aimStorageStockParamA.setDeliverId(deliverid);//交付id
                    aimStorageStockParamA.setDeptId(deptid);//部门id
                    storageStockService.update(aimStorageStockParamA);
                    try {
        				storageStockDetailedService.addNewDetailed("合托", "", "移入", "移入："+b1.toString(), aimStorageStockParamA,user);//新增 库存流水
					} catch (Exception e) {
					}
                }

            }
        }
        return ResponseData.success();
    }
    
    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/cxlist")
    public LayuiPageInfo list(MovingPalletsmergeParam movingPalletsmergeParam, String condition) {
    	User user = userAop.getUser();
    	movingPalletsmergeParam.setDeptId(user.getDeptId());
    	movingPalletsmergeParam.setDeliverId(user.getDeliverId());
    	LayuiPageInfo LayuiPageInfo = this.movingPalletsmergeService.findPageBySpec(movingPalletsmergeParam, condition,user.getOperateId());
    	LayuiPageInfo.setCode(200);
        return LayuiPageInfo;
    }

	@Autowired
    private DeptService deptService;
	
	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

    /**
     * 生成新托盘
     * @return
     */
    public BasicTrayResult addTray() {
    	User user = userAop.getUser();
        //托盘信息
        BasicTrayParam Tp = new BasicTrayParam();
        BasicTray basicTray = basicTrayService.findByThelastone();
        Tp.setTrayState("占用");//托盘状态
		String trayCode = getOperateIdOrderPrefix(user)+"-";
        int TrayNumber = 0;
        if (basicTray != null) {
            TrayNumber = (basicTray.getId() + 1);
        } else {
            TrayNumber = 1;
        }
        Tp.setDeliverId(user.getDeliverId());
        Tp.setDeptId(user.getDeptId());

		BasicTrayParam trayParam = new BasicTrayParam();
		trayParam.setDeliverId(user.getDeliverId());
		trayParam.setDeptId(user.getDeptId());
		trayParam.setTrayState("闲置");
		BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
		if(basicTrayResult != null) {
			ToolUtil.copyProperties(basicTrayResult, trayParam);
			trayParam.setTrayState("占用");
			basicTrayService.update(trayParam);
			return basicTrayResult;
		} else {
			Tp.setTrayNumber(trayCode+TrayNumber);
			trayParam.setTrayNumber(trayCode+TrayNumber);
			basicTrayService.add(Tp);
			trayParam.setTrayState("占用");
			basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
		}
        return basicTrayResult;
    }




}
